define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstree'], function ($, undefined, Backend, Table, Form, undefined) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'subscribe/index' + location.search,
                    add_url: 'subscribe/add',
                    edit_url: 'subscribe/edit',
                    del_url: 'subscribe/del',
                    multi_url: 'subscribe/multi',
                    import_url: 'subscribe/import',
                    table: 'subscribe',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'clinicname', title: __('Clinicname'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'totalprice', title: __('Totalprice'), operate:'BETWEEN'},
                        {field: 'date', title: __('Date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'time', title: __('Time')},
                        {field: 'firstname', title: __('Firstname'), operate: 'LIKE'},
                        {field: 'lastname', title: __('Lastname'), operate: 'LIKE'},
                        {field: 'email', title: __('Email'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'phone', title: __('Phone'), operate: 'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function (value, row, index) {
                            var table = this.table;
                            // 操作按钮
                            var buttons = [];
                            buttons.push({
                                name: 'view',
                                text: __('View'),
                                title: __('View'),
                                classname: 'btn btn-xs btn-info btn-view',
                                icon: 'fa fa-eye',
                                url: 'subscribe/edit'
                            });
                            buttons.push({
                                name: 'del',
                                text: __('Delete'),
                                title: __('Delete'),
                                classname: 'btn btn-xs btn-danger btn-delone',
                                icon: 'fa fa-trash',
                                url: 'subscribe/del',
                                confirm: __('Are you sure you want to delete this item?'),
                                success: function (data, ret) {
                                    Layer.alert(ret.msg);
                                    return false;
                                },
                                error: function (data, ret) {
                                    Layer.alert(ret.msg);
                                    return false;
                                }
                            });
                            return Table.api.formatter.operate.call(this, value, row, index, buttons);
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            
            // 初始化项目树状图
            if (typeof nodeData !== 'undefined') {
                Controller.api.initItemTree();
            }
        },
        edit: function () {
            Controller.api.bindevent();
            
            // 初始化项目树状图
            if (typeof nodeData !== 'undefined') {
                Controller.api.initItemTree();
            }
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            
            // 初始化项目树状图
            initItemTree: function () {
                // 渲染树状图
                Controller.api.rendertree(nodeData);
                
                // 显示已选项目的数量信息
                if (selectedIds && selectedIds.length > 0) {
                    setTimeout(function() {
                        Controller.api.updateSelectedItemsInfo();
                    }, 100);
                }
                
                // 编辑模式下允许用户修改选择
                // 不需要禁用节点，让用户可以自由选择/取消选择
                
                // 展开/折叠功能
                $(document).on("click", "#expandall", function () {
                    $("#treeview").jstree($(this).prop("checked") ? "open_all" : "close_all");
                });
                
                // 监听节点选择变化（只在添加页面启用）
                if (window.location.href.indexOf('/edit') === -1) {
                    $("#treeview").on('select_node.jstree', function (e, data) {
                        var nodeId = data.node.id;
                        if (selectedIds.indexOf(nodeId) === -1) {
                            selectedIds.push(nodeId);
                            if (!selectedCounts[nodeId]) {
                                var itemData = Controller.api.findItemData(nodeData, nodeId);
                                if (itemData && itemData.itemprice == 0) {
                                    selectedCounts[nodeId] = 0;
                                } else {
                                    selectedCounts[nodeId] = 1;
                                }
                            }
                            // 设置选中节点的背景色
                            $('.jstree-node.jstree-selected').css('background-color', '#eeeeee');
                            Controller.api.updateSelectedItemsInfo();
                            Controller.api.updateTotalPrice();
                            Controller.api.updateHiddenField();
                            // 更新树状图显示
                            Controller.api.updateTreeDisplay();
                        }
                    });
                    
                    // 监听节点取消选择
                    $("#treeview").on('deselect_node.jstree', function (e, data) {
                        var nodeId = data.node.id;
                        var index = selectedIds.indexOf(nodeId);
                        if (index > -1) {
                            selectedIds.splice(index, 1);
                            delete selectedCounts[nodeId];
                            // 恢复未选中节点的默认背景色
                            $('.jstree-node:not(.jstree-selected)').css('background-color', '');
                            Controller.api.updateSelectedItemsInfo();
                            Controller.api.updateTotalPrice();
                            Controller.api.updateHiddenField();
                            // 更新树状图显示
                            Controller.api.updateTreeDisplay();
                        }
                    });
                }
            },
            
            // 渲染树状图
            rendertree: function (content) {
                $("#treeview")
                    .on('redraw.jstree', function (e) {
                        $(".layer-footer").attr("domrefresh", Math.random());
                    })
                    .jstree({
                        "themes": {
                            "stripes": true,
                            "dots": true,
                            "icons": true
                        },
                        // 移除checkbox配置，使用自定义选择逻辑
                        "types": {
                            "folder": {
                                "icon": "fa fa-folder-open",
                            },
                            "file": {
                                "icon": "fa fa-file-o",
                            }
                        },
                        "plugins": ["types"],
                        "core": {
                            'check_callback': function(operation, node, parent, position, more) {
                                // 只允许选中/取消选中当前节点，不允许级联操作
                                if (operation === 'check_node' || operation === 'uncheck_node') {
                                    return true;
                                }
                                return true;
                            },
                            "data": content
                        }
                    })
                    .on('ready.jstree', function(e, data) {
                        // 树状图加载完成后，为预约中的项目设置背景色
                        if (selectedIds && selectedIds.length > 0) {
                            selectedIds.forEach(function(id) {
                                var node = $("#treeview").jstree("get_node", id);
                                if (node) {
                                    $("#" + node.id).css('background-color', '#eeeeee');
                                }
                            });
                        }
                    });
            },
            
            // 移除onTreeSelectionChanged方法，使用select_node和deselect_node事件
            
            // 更新树状图显示
            updateTreeDisplay: function () {
                // 更新树状图中节点的文本显示
                selectedIds.forEach(function(id) {
                    var itemData = Controller.api.findItemData(nodeData, id);
                    var count = selectedCounts[id] || 0;
                    if (itemData) {
                        var node = $("#treeview").jstree("get_node", id);
                        if (node) {
                            var newText = itemData.itemname + ' (¥' + itemData.itemprice + ')';
                            if (count > 0) {
                                newText += ' [× ' + count + ']';
                            }
                            $("#treeview").jstree("rename_node", node, newText);
                        }
                    }
                });
            },
            
            // 更新选中项目信息显示
            updateSelectedItemsInfo: function () {
                // 编辑页面不显示蓝色背景信息框
                if (window.location.href.indexOf('/edit') > -1) {
                    $("#selected-items-info").html('');
                    return;
                }
                
                var infoHtml = '';
                
                if (selectedIds.length > 0) {
                    infoHtml = '<div class="alert alert-info"><strong>已选项目：</strong><br>';
                    selectedIds.forEach(function(id) {
                        var itemData = Controller.api.findItemData(nodeData, id);
                        var count = selectedCounts[id] || 0;
                        
                        if (itemData) {
                            infoHtml += '<div class="row mb-1">';
                            infoHtml += '<div class="col-md-6">' + itemData.itemname + ' (¥' + itemData.itemprice + ')</div>';
                            infoHtml += '<div class="col-md-3">数量: <input type="number" min="0" class="form-control input-sm item-count" data-id="' + id + '" value="' + count + '" style="width: 60px; display: inline-block;"></div>';
                            infoHtml += '<div class="col-md-3">小计: ¥' + (parseFloat(itemData.itemprice) * count).toFixed(2) + '</div>';
                            infoHtml += '</div>';
                        }
                    });
                    infoHtml += '</div>';
                }
                $("#selected-items-info").html(infoHtml);
                
                // 更新树状图中的数量显示（只在添加页面）
                if (window.location.href.indexOf('/edit') === -1) {
                    Controller.api.updateTreeDisplay();
                }
                
                // 绑定数量输入事件
                $(".item-count").off('change').on('change', function() {
                    var id = $(this).data('id');
                    var count = parseInt($(this).val()) || 0;
                    if (count < 0) {
                        count = 0;
                        $(this).val(0);
                    }
                    selectedCounts[id] = count;
                    Controller.api.updateTotalPrice();
                    Controller.api.updateHiddenField();
                    // 更新树状图显示
                    Controller.api.updateTreeDisplay();
                });
            },
            
            // 更新总价格（根据选中的项目计算）
            updateTotalPrice: function () {
                var totalPrice = 0;
                var priceInput = $("#c-totalprice");
                
                // 遍历选中的项目，计算总价格（只计算数量大于0的项目）
                selectedIds.forEach(function(id) {
                    var itemData = Controller.api.findItemData(nodeData, id);
                    var count = selectedCounts[id] || 0;
                    if (itemData && itemData.itemprice && count > 0) {
                        totalPrice += parseFloat(itemData.itemprice) * count;
                    }
                });
                
                // 更新总价格输入框
                priceInput.val(totalPrice.toFixed(2));
            },
            
            // 更新隐藏字段
            updateHiddenField: function () {
                var itemData = [];
                selectedIds.forEach(function(id) {
                    var count = selectedCounts[id] || 0;
                    itemData.push({
                        id: parseInt(id),
                        count: parseInt(count)
                    });
                });
                
                var hiddenField = $("#c-itemids-hidden");
                if (hiddenField.length > 0) {
                    hiddenField.val(JSON.stringify(itemData));
                }
            },
            
            // 在树状图数据中查找项目信息
            findItemData: function (data, id) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].id == id) {
                        return data[i].data;
                    }
                    if (data[i].children && data[i].children.length > 0) {
                        var result = Controller.api.findItemData(data[i].children, id);
                        if (result) {
                            return result;
                        }
                    }
                }
                return null;
            }
        }
    };
    return Controller;
});
